package org.unidata.mdm.meta.service.segments;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.unidata.mdm.core.util.SecurityUtils;
import org.unidata.mdm.draft.context.DraftUpsertContext;
import org.unidata.mdm.draft.dto.DraftUpsertResult;
import org.unidata.mdm.draft.type.Draft;
import org.unidata.mdm.draft.type.Edition;
import org.unidata.mdm.meta.context.UpsertDataModelContext;
import org.unidata.mdm.meta.module.MetaModule;
import org.unidata.mdm.meta.service.impl.data.DataModelComponent;
import org.unidata.mdm.meta.type.draft.ModelDraftConstants;
import org.unidata.mdm.meta.type.instance.DataModelInstance;
import org.unidata.mdm.meta.type.model.DataModel;
import org.unidata.mdm.system.type.pipeline.Finish;
import org.unidata.mdm.system.type.pipeline.Start;
import org.unidata.mdm.system.type.variables.Variables;

/**
 * @author maria.chistyakova
 * @since  13.01.2020
 */
@Component(ModelDraftUpsertFinishExecutor.SEGMENT_ID)
public class ModelDraftUpsertFinishExecutor extends Finish<DraftUpsertContext, DraftUpsertResult> {
    /**
     * This segment ID.
     */
    public static final String SEGMENT_ID = MetaModule.MODULE_ID + "[MODEL_DRAFT_UPSERT_FINISH]";
    /**
     * Localized message code.
     */
    public static final String SEGMENT_DESCRIPTION = MetaModule.MODULE_ID + ".model.draft.upsert.finish.description";
    /**
     * The DMC.
     */
    @Autowired
    private DataModelComponent dataModelComponent;
    /**
     * Constructor.
     */
    public ModelDraftUpsertFinishExecutor() {
        super(SEGMENT_ID, SEGMENT_DESCRIPTION, DraftUpsertResult.class);
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public DraftUpsertResult finish(DraftUpsertContext ctx) {

        Draft draft = ctx.currentDraft();
        DraftUpsertResult result = new DraftUpsertResult(true);

        // 1. Set draft to result
        result.setDraft(draft);

        // 2. Take snapshot of current upon draft creation
        if (!draft.isExisting()) {

            String storageId = ctx.hasParameter(ModelDraftConstants.STORAGE_ID)
                    ? ctx.getParameter(ModelDraftConstants.STORAGE_ID)
                    : SecurityUtils.getCurrentUserStorageId();

            DataModelInstance i = dataModelComponent.instance(storageId, null);

            result.setVariables(variables(i));
            result.setEdition(snapshot(i));
        }

        // 3. The following stuff runs only, if some data were supplied
        if (ctx.hasPayload()) {
            result.setEdition(edit(draft, ctx.getPayload()));
        }

        return result;
    }

    protected Edition snapshot(DataModelInstance i) {

        Edition next = new Edition();
        next.setContent(i.toSource());
        next.setCreateDate(new Date(System.currentTimeMillis()));
        next.setCreatedBy(SecurityUtils.getCurrentUserName());

        return next;
    }

    protected Edition edit(Draft draft, UpsertDataModelContext input) {

        input.currentDraft(draft);
        DataModel changes = dataModelComponent.assemble(input);

        Edition next = new Edition();
        next.setContent(changes);
        next.setCreateDate(new Date(System.currentTimeMillis()));
        next.setCreatedBy(SecurityUtils.getCurrentUserName());

        return next;
    }

    protected Variables variables(DataModelInstance i) {

        return new Variables()
                .add(ModelDraftConstants.DRAFT_INITIATOR, SecurityUtils.getCurrentUserName())
                .add(ModelDraftConstants.STORAGE_ID, i.getStorageId())
                .add(ModelDraftConstants.DRAFT_START_VERSION, i.getVersion());
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public boolean supports(Start<?, ?> start) {
        return DraftUpsertContext.class.isAssignableFrom(start.getInputTypeClass());
    }
}
